import {parseParam} from '@/util/param';

// 辅助工具类
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 


export const ApiResult = {
	success(data) {
		return {
			success: true,
			data: data,
		}
	},
	failure(message) {
		return {
			success: false,
			message: message,
		}
	}
};

export const bodyToObj = body => {
	if (!body) return {};
	
	if (typeof(body) === "object") {
		return body;
	}
	return JSON.parse(body);
};

export const parseSceneBy = string => {
	return parseParam(decodeURIComponent(string));
};

export const parseSceneByOptionsUrl = options => {
	return parseSceneBy(options.url);
};

export const parseSceneByOptionsBody = options => {
	return bodyToObj(options.body);
};

export const arrayToMap = (items, keyAttr='id') => {
	const temp = {};
	
	items.forEach(item => temp[item[keyAttr]] = item);
	
	return temp;
};

// 删除数组中指定元素，成功返回被删元素
export const deleteArrayElementBy = (items, predicate) => {
	let item = items.find(predicate);
	// 未找到指定元素
	if (!item) return;
	
	// 查询元素在数组中的位置
	let index = items.indexOf(item);
	
	if (index > -1) {
		// 删除元素
		items.splice(index, 1);
	}
	return item;
};

export const deleteArrayElementByKv = (items, attr, value) => {
	deleteArrayElementBy(items, item => item[attr] == value);
};


export const PageData = (items=[], pageNumber=1, pageSize=10) => {
	if (pageNumber < 1) pageNumber = 1;
	if (pageSize < 1) pageSize = 10;
	
	let start = (pageNumber - 1) * pageSize;
	let end = start + pageSize;
	let list = items.slice(start, end);
	
	return {
		firstPage: 1 == pageNumber,
		lastPage: end >= items.length,
		totalPage: Math.ceil(items.length / pageSize),
		totalRow: items.length,
		list: list,
	};
};

// 将数组根据参数转化为page格式数据
export const toPageData = (items, param) => {
	const noneData = PageData();
	
	if (!items) return noneData;
	
	if (!Array.isArray(items)) {
		console.error("items mast be array!");
		return noneData;
	}
	
	return ApiResult.success(PageData(items, param.pageNumber, param.pageSize));
};


export default {
	ApiResult,
	bodyToObj,
	parseSceneBy,
	parseSceneByOptionsUrl,
	parseSceneByOptionsBody,
	arrayToMap,
	deleteArrayElementBy,
	deleteArrayElementByKv,
	PageData,
	toPageData,
}
